package cc.orange.mainView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.databinding.DataBindingUtil;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cc.orange.BuildConfig;
import cc.orange.R;
import cc.orange.base.BaseFragment;
import cc.orange.databinding.FragmentMineBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.entity.LoginsEntity;
import cc.orange.entity.LoginsGetEntity;
import cc.orange.entity.UserInfoEntity;
import cc.orange.entity.WxInfoEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.popup.PopupLoginsView;
import demo.smart.access.xutlis.util.ZXAppUtil;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import demo.smart.access.xutlis.util.ZXSystemUtil;
import cc.orange.utils.ZXToastUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static cc.orange.http.ApiService.HOST;

public class MineFragment extends BaseFragment implements View.OnClickListener{

    private FragmentMineBinding binding;
    private boolean isLogin = false;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_mine,container,false);
        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
        isLogin = ss.getBool("isLogin_talk",false);
        initView();
        getSuserInfo(0);
        EventBus.getDefault().register(this);
        return binding.getRoot();
    }

    private void initView() {
        binding.mineText11.setOnClickListener(this);
        binding.mineImg1.setOnClickListener(this);
        binding.mineRel5.setOnClickListener(this);
        binding.mineRel8.setOnClickListener(this);
        binding.mineText1.setOnClickListener(this);
        binding.mineImg11.setOnClickListener(this);

        binding.settingClick10.setOnClickListener(this);
        binding.settingText4.setText("v"+ ZXAppUtil.getAppVersionName());
        binding.settingClick1.setOnClickListener(this);
        binding.settingClick2.setOnClickListener(this);
        binding.settingClick3.setOnClickListener(this);
        binding.settingClick4.setOnClickListener(this);
        binding.settingClick5.setOnClickListener(this);
        binding.settingClick6.setOnClickListener(this);
        binding.settingClick7.setOnClickListener(this);
        binding.settingClick11.setOnClickListener(this);


        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
        boolean putswitch = ss.getBool("putswitch_talk", false);
        binding.mineSwitch.setChecked(putswitch);

        binding.mineSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(!isLogin){
                    ZXToastUtil.showToast("请先登录");
                    binding.mineSwitch.setChecked(!isChecked);
                    return;
                }
                ss.putBool("putswitch_talk", binding.mineSwitch.isChecked());
            }
        });
    }

    @Override
    public void onClick(View v) {
        if(!isLogin && v.getId() != R.id.mine_img1 && v.getId() != R.id.mine_text1){
            ZXToastUtil.showToast("请先登录");
            return;
        }
        switch (v.getId()){
            case R.id.mine_text11:
                startActivity(new Intent(getActivity(),WalletActivity.class));
                break;
            case R.id.mine_text1:
            case R.id.mine_img1:
            case R.id.mine_img1_1:
                if (!isLogin) {
                    startActivity(new Intent(getActivity(),LonginWxActivity.class));
                }
                break;
            case R.id.setting_click10:
            case R.id.mine_rel5:
//                startActivity(new Intent(getActivity(),MyGradeActivity.class));
                break;
            case R.id.mine_rel8:
                startActivity(new Intent(getActivity(),SettingActivity.class));
                break;

            case R.id.setting_click1:
                WebViewActivity.openH5Activity(getActivity(),"用户协议", BuildConfig.WEBS_URL1);
                break;
            case R.id.setting_click2:
                WebViewActivity.openH5Activity(getActivity(),"隐私政策",BuildConfig.WEBS_URL2);
                break;
            case R.id.setting_click3:
//                showDialogs(2);
                Intent intent = new Intent(getActivity(), Conversation4KFActivity.class);
                startActivity(intent);
                break;
            case R.id.setting_click4:
                break;
            case R.id.setting_click5:
                getSuserInfo(1);
                break;
            case R.id.setting_click6:
                WebViewActivity.openH5Activity(getActivity(),"应用权限说明",BuildConfig.WEBS_URL3);
                break;
            case R.id.setting_click7:
                showDialogs(1);
                break;
            case R.id.setting_click11:
                showDialogs(2);
                break;
        }
    }

    private void showDialogs(int type){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());       //
        builder.setTitle("");// 设置对话框的标题
        if(type == 1){
            builder.setMessage("确定要注销账号吗？账号注销后，您的所有信息将被清除");
        }else{
            builder.setMessage("确定要退出登录吗？");
        }

        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(type == 1){
                    deleteUser();
                }else{
                    ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                    ss.clear();
                    EventBus.getDefault().post(new IsLoginsEntity(false));
                    ZXToastUtil.showToast("账号已退出");
                }
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }


    private void deleteUser() {
        RetrofitFactory.create(ApiService.class)
                .deleteUser(getTokens())
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            ss.clear();
                            EventBus.getDefault().post(new IsLoginsEntity(false));
                            ZXToastUtil.showToast("账号注销成功");
                        } else {
//                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(IsLoginsEntity entity){
        if(!entity.isLogins()){
            isLogin = false;
            binding.mineImg1.setImageResource(0);
            binding.mineText1.setText("请先登录");
            binding.mineText2.setText("");
            binding.mineImg21.setVisibility(View.GONE);
            binding.mineImg2.setVisibility(View.GONE);
            binding.discItemRel2.setVisibility(View.GONE);
            binding.discItemRel3.setVisibility(View.GONE);
            Glide.with(getActivity()).load(R.color.black).into(binding.mineImg1);

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getLogisnMsg(WxInfoEntity wxInfoEntity){
        if(wxInfoEntity.getSex() == 0){
            getLogin(wxInfoEntity.getOpenid(),wxInfoEntity.getNickname(),
                    wxInfoEntity.getHeadimgurl(),"1");
        }else{
            PopupLoginsView.showPopupwindow(getActivity(), binding.mineImg1, new PopupLoginsView.PopuStatus() {
                @Override
                public void popupShow() {
                }
                @Override
                public void popupDismissCancle(String se) {
                    if(se.equals("2")){
                        getLogin(wxInfoEntity.getOpenid(),wxInfoEntity.getNickname(),
                                wxInfoEntity.getHeadimgurl(),"1");
                    }
                }
            });
        }
    }


    private void getLogin(String openid,String name,String url,String sex){
        LoginsGetEntity entitys = new LoginsGetEntity(openid,name,url,sex);
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .login(requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            ss.putString("token_talk",baseEntity.getData());
                            ss.putBool("isLogin_talk",true);
                            isLogin = true;
                            Glide.with(getActivity()).load(url).into(binding.mineImg1);
                            ss.putString("name_talk",name);
                            ss.putString("openid_talk",openid);
                            ss.putString("url_talk",url);
                            binding.mineText1.setText(name);
                            ZXToastUtil.showToast("登录成功");
                            EventBus.getDefault().post(new IsLoginsEntity(true));
                            getSuserInfo(0);

//                            TalkingDataProfile profile = TalkingDataProfile.createProfile();
//                            profile.setName(name);
//                            profile.setType(TalkingDataProfileType.WEIXIN);
//                            profile.setGender(sex.equals("0") ? TalkingDataGender.MALE : TalkingDataGender.FEMALE);
//                            TalkingDataSDK.onLogin(openid,profile);
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void getSuserInfo(int type){

        RetrofitFactory.create(ApiService.class)
                .getSuserInfo(getTokens())
                .enqueue(new DefaultCallback<UserInfoEntity>() {
                    @Override
                    public void onStart(Call<UserInfoEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<UserInfoEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<UserInfoEntity> call, UserInfoEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            Glide.with(getActivity()).load(baseEntity.getData().getHeadPhoto()).into(binding.mineImg1);
                            ss.putString("name_talk",baseEntity.getData().getName());
                            ss.putString("openid_talk",baseEntity.getData().getOpenId());
                            ss.putString("url_talk",baseEntity.getData().getHeadPhoto());
                            ss.putString("id_talk",""+baseEntity.getData().getId());
                            binding.mineText1.setText(baseEntity.getData().getName());
                            binding.mineText2.setText("ID"+baseEntity.getData().getNumber());
                            binding.mineText4.setText(""+baseEntity.getData().getGzNum());
                            binding.mineText5.setText(""+baseEntity.getData().getFsNum());
                            binding.mineText4.setText(""+baseEntity.getData().getLfNum());

                            binding.mineImg21.setVisibility(View.VISIBLE);
                            binding.mineImg2.setVisibility(View.VISIBLE);
                            binding.discItemRel2.setVisibility(View.VISIBLE);
                            binding.discItemRel3.setVisibility(View.VISIBLE);
                            binding.mineImg2.setImageResource(baseEntity.getData().getSex() == 0 ?
                                    R.drawable.icon_disc_sex0 : R.drawable.icon_disc_sex1);
                            if(type == 1) {
                                if (baseEntity.getData().getVersionCode() > ZXSystemUtil.getVersionCode()) {
//                                EventBus.getDefault().post(new String("uploa_"+baseEntity.getData().getDownload()));
//                                EventBus.getDefault().post(new String("uploa_"+ HOST+"/api/load/download/"+getNems()));
//                                EventBus.getDefault().post(new String("uploa_https://sdfdf/asdfdsaf"));
                                    ZXToastUtil.showToast("当前以是最新版本");
                                } else {
                                    ZXToastUtil.showToast("当前以是最新版本");
                                }
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }



    @Override
    public void onResume() {
        super.onResume();
//        TalkingDataSDK.onPageBegin(getActivity().getApplicationContext(), this.toString());
    }

    @Override
    public void onPause() {
        if(!this.isHidden()){
//            TalkingDataSDK.onPageEnd(getActivity().getApplicationContext(), this.toString());
        }
        super.onPause();
    }
}